/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameheart.transport;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.*;
import org.w3c.dom.*;

/**
 *
 * @author win7
 */
public class NetworkTransporter implements Transporter {

    private BufferedReader reader;
    private BufferedWriter writer;

    public NetworkTransporter(Socket socket) throws MyException {
        InputStream is;
        try {
            is = socket.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is));
            OutputStream os = socket.getOutputStream();
            writer = new BufferedWriter(new OutputStreamWriter(os));
        } catch (IOException ex) {
            Logger.getLogger(NetworkTransporter.class.getName()).log(Level.SEVERE, null, ex);
            throw new MyException();
        }
    }
    private XmlProcessor _processor = new XmlProcessor();

    public void SendCommand(Command command) throws MyException {
        try {
            String xmlString = _processor.convertToXmlString(command);
            writer.write(xmlString);
            writer.newLine();
            writer.flush();
        } catch (IOException ex) {
            Logger.getLogger(NetworkTransporter.class.getName()).log(Level.SEVERE, null, ex);
            throw new MyException();
        }


    }

    public Command GetCommand(boolean waiting) throws MyException {
        Command command = null;
        try {
            if (waiting) {
                String receiveMessage = reader.readLine();
                command = _processor.parseMessage(receiveMessage);
            } else {
                if (reader.ready()) {
                    String receiveMessage = reader.readLine();
                    command = _processor.parseMessage(receiveMessage);
                }
            }
        } catch (IOException ioEx) {
            Logger.getLogger(NetworkTransporter.class.getName()).log(Level.SEVERE, null, ioEx);
            throw new MyException();
        }
        return command;
    }
}
